/*
 * @Author: jiayu
 * @Date: 2022-08-04 16:12:56
 * @LastEditors: jiayu
 * @LastEditTime: 2023-11-07 17:02:17
 * @Description:
 */
import Card from '@/components/Card';
import { Bar } from '@ant-design/plots';
import { Button, Popover, DatePicker } from 'antd';
import { Dispatch, memo, SetStateAction, useEffect, useState } from 'react';
import styles from './index.less';

import { FullscreenOutlined, FullscreenExitOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import React from 'react';
import { useModel } from '@umijs/max';
import { instance } from '@/services/jy-api/api';
import moment from 'moment';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';

const RightContentRender: React.FC<ChartSctionProps> = (props) => {
  const { isModal, full, fullHandle, dateChange, defaultDeteValue } = props
  const goToFullScreen = (element) => {// 定义名为 "goToFullScreen" 的函数，并接受一个参数 "element"。
    element = element || document.body;// 如果传入 "element" 参数则以该元素为目标，否则为整个文档体 "document.body"
    if (element.requestFullscreen) {// 判断是否支持 W3C 标准的请求全屏接口
      element.requestFullscreen();// 通过调用 requestFullscreen() 方法来请求进入全屏模式
    } else if (element.mozRequestFullScreen) {// 判断是否支持 moz 的非标准客户端 API 请求接口
      element.mozRequestFullScreen();// 通过调用 mozRequestFullScreen() 方法来请求进入全屏模式
    } else if (element.msRequestFullscreen) {// 判断是否支持 Microsoft 提供的 PC Edge 浏览器和 IE11 浏览器专属 Api 接口
      element.msRequestFullscreen();// 通过调用 msRequestFullscreen() 方法来请求进入全屏模式
    } else if (element.webkitRequestFullscreen) {// 判断是否支持 Webkit 内核标准请求接口
      element.webkitRequestFullScreen();// 通过调用 webkitRequestFullScreen() 方法来请求进入全屏模式
    }
  };
  const click = () => {
    if (isModal) {
      full && full(false)
    } else {
      fullHandle && fullHandle('section8')
      full && full(true)
    }
  }
  return <div className={styles.rightToolBar}>
    <RangePicker defaultValue={defaultDeteValue} format={dateFormat} style={{ marginRight: 10 }} onChange={dateChange} />
    <Button icon={isModal ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={click}></Button>
  </div>
}

export interface ChartSctionProps {
  isModal?: boolean,
  full?: Dispatch<SetStateAction<boolean>>
  fullHandle?: (val: string) => void
  dateChange?: (val: any) => void,
  defaultDeteValue: any
}
const Index: React.FC<ChartSctionProps> = memo((props) => {
  const [config, setConfig] = useState<any>()
  const [datePick, setDatePick] = useState([moment(moment().add(-6, 'M'), dateFormat), moment(moment(), dateFormat)])
  const [testId, setTestId] = useState('')
  const [testName, setTestName] = useState('')
  const Title = () => {
    return <div className={styles.titleContainer}>
      <div className={styles.title}>考试统计</div>
      {/* <Popover content="培训课程平均学习时长描述了该部门的平均每人每月的学习时长(所有人学习总时长÷人数)"> */}
      {/* <ExclamationCircleOutlined className={styles.icon} /> */}
      {/* </Popover> */}
    </div>
  }

  const dateChange = (e) => {
    e && setDatePick(e)
  }

  const getData = () => {
    instance('index/Screen/examinationTj', {
      params: {
        stime: moment(datePick[0]).format('YYYY-MM-DD'),
        etime: moment(datePick[1]).format('YYYY-MM-DD'),
      }
    }).then(data => {
      if (!data.data) {
        return
      }
      setTestId(data.data[0].id)
      setTestName(data.data[0].title)
      const _data = data.data ? data.data.reduce((prev, current) => {
        const list = current.score_fraction.score.map((item, index) => {
          const names = ['不及格', '及格', '良好', '优秀']
          return {
            name: current.title,
            num: current.score_fraction.rate[index],
            status: names[index],
            id: current.id
          }
        })
        return [...prev, ...list]
      }, []) : []
      const _config = {
        // theme: 'dark',
        data: _data,
        xField: 'num',
        yField: 'name',
        seriesField: 'status',
        isPercent: true,
        isStack: true,
        xAxis: {
          label: {
            // 数值格式化为千分位
            formatter: (v: any) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
          },
          grid: {
            line: {
              style: {
                stroke: '#8291A9',
                lineWidth: 1,
                lineDash: [4, 5],
                strokeOpacity: 0.7,
              }
            }
          }
        },
        yAxis: {
          label: {
            style: {
              fill: '#ffffff',
              fontSize: 14
            },
          },
        },
        /** 自定义颜色 */
        color: ['#c52125', '#2582a1', '#f88c24', '#87f4d0'],
        label: {
          position: 'middle',
          content: (item) => {
            if (item.num == 0) {
              return null
            }
            return item.num.toFixed(2);
          },
          style: {
            fill: '#fff',
          },
        },
        legend: {
          flipPage: false,
          itemName: {
            style: {
              fill: '#ffffff',
              fontSize: 14
            },
          },
          position: 'top-left',
          marker: {
            style: (x: { r: 5, fill: '#5AD8A6', fillOpacity: 1, stroke: null }) => {
              return {
                ...x,
                r: 10,
              }
            },
          }
        }
      }
      setConfig(_config)
    })
  }

  useEffect(() => {
    getData()
  }, [datePick])

  return (
    <div className={styles.section} id="section8">
      <Card TitleRnder={<Title />} RightContentRender={<RightContentRender {...props} dateChange={dateChange} defaultDeteValue={datePick} />}>
        <div className={styles.container}>
          <div className={styles.left}>
            {config && <Bar height={300}
              {...config} onReady={(plot) => {
                plot.on('plot:click', (evt) => {
                  const { x, y } = evt;
                  const { xField } = plot.options;
                  const tooltipData = plot.chart.getTooltipItems({ x, y });
                  console.log({ tooltipData, xField, evt })
                  setTestName(tooltipData[0].title)
                  setTestId(tooltipData[0].data.id)
                });
              }} />}
          </div>
          <div className={styles.right}>
            <div className={styles.title}>"{testName}"考试成绩排名</div>
            <Chart2 id={testId} />
          </div>
        </div>
      </Card>
    </div>
  );
});

const Chart2 = (props: {
  id: string,
}) => {
  const {
    id
  } = props
  const [config, setConfig] = useState<any>()
  const getData = () => {
    instance('/index/Screen/testScore', {
      params: {
        id
      }
    }).then(data => {
      const _config = {
        appendPadding: [0, 38, 0, 0],
        data: data.data ? data.data.sort((a, b) => b.learn_time - a.learn_time).slice(0, 10) : [],
        xField: 'score',
        yField: 'nickname',
        seriesField: 'nickname',
        legend: false,
        interactions: [{ type: 'element-active' }],
        maxBarWidth: 20,
        label: {
          // 可手动配置 label 数据标签位置
          position: 'right',
          offset: 4,
          style: {
            fill: '#ffffff',
            fontSize: 12
          },
          formatter: (v: any) => {
            return v.score + '分'
          },
        },
        barStyle: {
          radius: [8, 8, 0, 0],
        },
        xAxis: {
          label: {
            // 数值格式化为千分位
            formatter: (v: any) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
          },
          grid: {
            line: {
              style: {
                stroke: '#8291A9',
                lineWidth: 1,
                lineDash: [4, 5],
                strokeOpacity: 0.7,
              }
            }
          }
        },
        state: {
          // 设置 active 激活状态的样式
          selected: {
            animate: { duration: 100, easing: 'easeLinear' },
            style: {
              lineWidth: 2,
              stroke: '#000',
            },
          },
        }
      }
      setConfig(_config)
    })
  }
  useEffect(() => {
    id && getData()
  }, [id])
  if (!config) {
    return null
  }
  return <Bar height={300} {...config} />;
}


export default Index;

